﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Diagnostics;
using System.Drawing;
using System.Threading.Tasks;

namespace Archiver.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Upload(int? chunk, string name, string album)
        {

            var fileUpload = Request.Files[0];
            var uploadPath = Server.MapPath("~/App_Data/" + album);

            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }

            chunk = chunk ?? 0;
            using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
            {
                Debug.WriteLine(string.Format("Chunk: {0}, Name: {1}, Size:{2}",
                    chunk ?? -1,
                    name,
                    fileUpload.InputStream.Length.ToString()));

                var buffer = new byte[fileUpload.InputStream.Length];
                fileUpload.InputStream.Read(buffer, 0, buffer.Length);
                fs.Write(buffer, 0, buffer.Length);
            }
            return Content("chunk uploaded", "text/plain");


        }




        [HttpPost]
        public void Thumbnail(string uploadedFilename, string albumName)
        {

            string uploadRoot = "App_Data";

            Task.Factory.StartNew((filename) =>
            {
                var pictureToken = ((string)filename).Split('.');
                
                var newDirectory = Server.MapPath(string.Format("~/{0}/{1}", uploadRoot, albumName));
                var newFilename = Server.MapPath(string.Format("/{0}/{1}", newDirectory, filename.ToString()));
                
                var thumbFilename = Server.MapPath(
                    string.Format("~/{0}/{1}/{2}",
                        uploadRoot,
                        albumName,
                        string.Format("{0}_thumb.{1}",
                            pictureToken.ElementAt(0),
                            pictureToken.ElementAt(1)))
                );


                if (Directory.Exists(newDirectory))
                {
                    Directory.CreateDirectory(newDirectory);
                }


                byte[] myByte = System.IO.File.ReadAllBytes(newFilename);
                Image i;

                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(myByte, 0, myByte.Length);
                    i = Image.FromStream(ms);
                }

                Image thumb = null;
                if (i.Width > i.Height)
                {
                    thumb = i.GetThumbnailImage(210, 150, () => false, IntPtr.Zero);
                }
                else
                {
                    thumb = i.GetThumbnailImage(150, 210, () => false, IntPtr.Zero);
                }

                thumb.Save(thumbFilename);

            }, uploadedFilename);
            //return File(imageToByteArray(), "image/jpeg");
        }

        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }
    }
}
